package com.mbigger.admin.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.mbigger.admin.common.RequestHolder;
import com.mbigger.admin.dao.RoleAclMapper;
import com.mbigger.admin.entity.RoleAcl;
import com.mbigger.admin.service.RoleAclService;
import com.mbigger.admin.util.IpUtil;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
public class RoleAclServiceImpl implements RoleAclService{

	@Autowired
	private RoleAclMapper roleAclMapper;

	public void changeRoleAcls(Integer roleId, List<Integer> aclIdList) {
		List<Integer> originAclIdList = roleAclMapper.getAclIdListByRoleIdList(Lists.newArrayList(roleId));
		if (originAclIdList.size() == aclIdList.size()) {
			Set<Integer> originAclIdSet = Sets.newHashSet(originAclIdList);
			Set<Integer> aclIdSet = Sets.newHashSet(aclIdList);
			originAclIdSet.removeAll(aclIdSet);
			if (CollectionUtils.isEmpty(originAclIdSet)) {
				return;
			}
		}
		updateRoleAcls(roleId, aclIdList);
	}

	@Transactional
	public void updateRoleAcls(int roleId, List<Integer> aclIdList) {
		roleAclMapper.deleteByRoleId(roleId);

		if (CollectionUtils.isEmpty(aclIdList)) {
			return;
		}
		List<RoleAcl> roleAclList = Lists.newArrayList();
		for (Integer aclId : aclIdList) {
			RoleAcl roleAcl = RoleAcl.builder().roleId(roleId).aclId(aclId)
					.operator(RequestHolder.getCurrentUser().getUsername())
					.operateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest())).operateTime(new Date()).build();
			roleAclList.add(roleAcl);
		}
		roleAclMapper.batchInsert(roleAclList);
	}
}
